import { Row, Flex } from 'antd';
import React, { useEffect, useLayoutEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
import { homeMenu, aboutMenu, testMenu } from '../../config/menu';
const Nav = ({ setItems }) => {
  const [currentKey, setCurrentKey] = useState();
  const location = useLocation();
  const { pathname } = location;
  useLayoutEffect(() => {
    const getPath = (arr) => {
      const result = [];
      const fn = (value) => {
        value.forEach((item) => {
          if (item.key) result.push(item.key);
          if (item.children) fn(item.children);
        });
      };
      fn(arr);
      return result;
    };
    let [homeMenuPathList, aboutMenuPathList, testMenuPathList] = [getPath(homeMenu), getPath(aboutMenu), getPath(testMenu)];
    if (homeMenuPathList.includes(pathname)) {
      removeItemSiShowItem(homeMenu);
      return setItems(homeMenu) || setCurrentKey('home');
    } else if (aboutMenuPathList.includes(pathname)) {
      removeItemSiShowItem(aboutMenu);
      return setItems(aboutMenu) || setCurrentKey('about');
    } else if (testMenuPathList.includes(pathname)) {
      removeItemSiShowItem(testMenu);
      return setItems(testMenu) || setCurrentKey('test');
    }
  }, []);
  const removeItemSiShowItem = (arr) => {
    const fn = (value) => {
      value.forEach((item, index, arr) => {
        if (item.show === 'false') {
          arr.splice(index, 1);
        }
        if (item.children) fn(item.children);
      });
    };
    fn(arr);
  };
  const navList = [
    {
      label: '首页',
      key: 'home',
      items: homeMenu,
    },
    {
      label: '关于',
      key: 'about',
      items: aboutMenu,
    },
    {
      label: '测试',
      key: 'test',
      items: testMenu,
    },
  ];
  const handleClick = (value) => {
    removeItemSiShowItem(value.items);
    value.key === currentKey ? null : setCurrentKey(value.key) || setItems(value.items);
  };

  return (
    <Flex gap="small" className=" pl-8 pr-8" style={{ marginRight: 'auto' }}>
      {navList.map((item) => {
        return (
          <div style={item.key === currentKey ? { color: '#1677ff' } : null} key={item.key} onClick={() => handleClick(item)}>
            {item.label}
          </div>
        );
      })}
    </Flex>
  );
};
export default Nav;
